package com.example.myapplication.BroadcastTest;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.media.MediaPlayer;
import android.widget.Toast;
import com.example.myapplication.R;

public class MusicBroadcastReceiver extends BroadcastReceiver {
  private MediaPlayer mediaPlayer;
  private int[] musicFile = { R.raw.test_music, R.raw.test_music2 };

  @Override public void onReceive(Context context, Intent intent) {


    String action = intent.getAction();

    if (action.equals(BroadcastTestActivity.ACTION_PLAY)) {
      if (mediaPlayer == null) {
        int songIndex = intent.getIntExtra("songIndex", 0);
        mediaPlayer = MediaPlayer.create(context, musicFile[songIndex]);
        mediaPlayer.setLooping(true);
      }
      //开始播放音乐
      if (!mediaPlayer.isPlaying()) {
        mediaPlayer.start();
        Toast.makeText(context, "开始播放", Toast.LENGTH_SHORT).show();
      }
    } else if (action.equals(BroadcastTestActivity.ACTION_PAUSE)) {
      //暂停音乐
      if (mediaPlayer != null && mediaPlayer.isPlaying()) {
        mediaPlayer.pause();
        Toast.makeText(context, "已暂停", Toast.LENGTH_SHORT).show();
      }
    } else if (action.equals(BroadcastTestActivity.ACTION_SWAP)) {
      //切换下一首
      if (mediaPlayer != null) {
        mediaPlayer.release();
      }
      //切换歌曲
      int songIndex = intent.getIntExtra("songIndex", 0);
      mediaPlayer = MediaPlayer.create(context, musicFile[songIndex]);
      mediaPlayer.setLooping(true);
      mediaPlayer.start();
      Toast.makeText(context, "已切换下一首", Toast.LENGTH_SHORT).show();
    } else if (action.equals(BroadcastTestActivity.ACTION_STOP)) {
      //停止音乐
      if (mediaPlayer != null) {
        mediaPlayer.stop();
        mediaPlayer.release();
        mediaPlayer = null;
        Toast.makeText(context, "已停止播放", Toast.LENGTH_SHORT).show();
      }
    }
  }
}
